package com.ycsj.goldmedalnewconcept.main.activity;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.ycsj.common.base.BaseActivity;
import com.ycsj.common.base.BaseApplication;
import com.ycsj.common.base.SpKeys;
import com.ycsj.common.http.HttpCallBack;
import com.ycsj.common.http.HttpUtils;
import com.ycsj.common.manager.CustomDialogManager;
import com.ycsj.common.utils.AESOperator;
import com.ycsj.common.utils.GsonUtil;
import com.ycsj.common.utils.SPUtil;
import com.ycsj.common.utils.ScreenUtils;
import com.ycsj.common.utils.SnackbarUtil;
import com.ycsj.common.utils.StateBarUtil;
import com.ycsj.common.utils.UiUtils;
import com.ycsj.common.view.cleanedittext.CommonEditText;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.util.StateCodeUtils;
import com.ycsj.goldmedalnewconcept.main.bean.LoginInfo;
import com.ycsj.goldmedalnewconcept.master.activity.MasterMainActivity;
import com.ycsj.goldmedalnewconcept.parent.activity.ParentMainActivity;
import com.ycsj.goldmedalnewconcept.student.activity.StudentGetpetOneActivity;
import com.ycsj.goldmedalnewconcept.student.activity.StudentMainActivity;
import com.ycsj.goldmedalnewconcept.teacher.activity.TeacherMainActivity;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;
import me.jessyan.autosize.internal.CancelAdapt;

/**
 * 登录界面
 * Created by Administrator on 2019/2/12 0012.
 * implements CancelAdapt这个接口表示该页面放弃适配
 */

public class LoginActivity extends BaseActivity implements CancelAdapt {
    @BindView(R.id.main)
    RelativeLayout main;
    @BindView(R.id.bt_login)
    Button btLogin;
    @BindView(R.id.lv_cjzh)
    ImageView lvCjzh;
    @BindView(R.id.et_tel)
    CommonEditText etTel;
    @BindView(R.id.et_pwd)
    CommonEditText etPwd;
    @BindView(R.id.lv_jzzh)
    ImageView mLvJzzh;

    //做动画的控件
    @BindView(R.id.lv_kl)
    ImageView lvKL;

    @BindView(R.id.lv_pc)
    ImageView lvPc;


    @BindView(R.id.lv_sun)
    ImageView lvSun;

    @BindView(R.id.lv_xone)
    ImageView xOne;

    @BindView(R.id.lv_xtwo)
    ImageView xTwo;

    @BindView(R.id.lv_xthree)
    ImageView xThree;


    //账号的整体布局
    @BindView(R.id.ll_account)
    LinearLayout llAccount;
    //密码的整体布局
    @BindView(R.id.ll_pwd)
    LinearLayout llPwd;


    //用户角色
    private String role;

    //是否记住账号的标记
    private boolean isRememberCount;

    //控件做动画的集合
    private AnimatorSet animatorSet;

    /**
     * AES秘钥
     */
    public String key = "aaaaaaaaaaaaaaaa";

    @Override
    protected int getContentLayout() {
        return R.layout.activity_login;
    }

    @Override
    protected void init() {

        //沉浸状态栏
        StateBarUtil.customImmerseBar(this);

        //动态定位页面布局位置
//        initLocation();

        //初始化状态值,根据是否记住账号
        syncState();

        //执行控件的动画
        doAnim();

        //设置监听
        initListener();

        //同步登录按钮的方法
        synvLoginState();
    }


    /**
     * 设置监听
     */
    private void initListener() {
        etTel.setListener(new CommonEditText.onAfterInputListener() {
            @Override
            public void after() {
                synvLoginState();
            }
        });
        etPwd.setListener(new CommonEditText.onAfterInputListener() {
            @Override
            public void after() {
                synvLoginState();
            }
        });
    }

    /**
     * 同步登录按钮的方法
     */
    private void synvLoginState() {
        String tel = etTel.getEdittext().getText().toString().trim();
        String pwd = etPwd.getEdittext().getText().toString().trim();
        if (TextUtils.isEmpty(tel) || TextUtils.isEmpty(pwd)) {
            btLogin.setBackgroundResource(R.drawable.login_un_dl);
            btLogin.setEnabled(false);
        } else {
            btLogin.setBackgroundResource(R.drawable.login_dl);
            btLogin.setEnabled(true);
        }
    }

    /**
     * 动态的定位账号和密码框的位置
     */
    private void initLocation() {
        //计算屏幕的高度,设计图的背景图宽高是750*1334,输入框的高度是
        int screenWidth = ScreenUtils.getScreenWidth(this);
        int screenHeight = ScreenUtils.getScreenHeight(this);
        //计算输入框的宽和高
        int accountWidth = screenWidth * 232 / 455;
        int accountHeight = screenHeight * 28 / 804;

        //计算账号整体的上边距和左边距以及宽高
        int accountMarginTop = screenHeight * 406 / 804;
        int accountMaringLeft = screenWidth * 102 / 455;
        RelativeLayout.LayoutParams lpAccount = new RelativeLayout.LayoutParams(accountWidth, accountHeight);
        lpAccount.topMargin = accountMarginTop;
        lpAccount.leftMargin = accountMaringLeft;
        llAccount.setLayoutParams(lpAccount);


        //计算密码整体的上边距和左边距以及宽高
        int pwdWidth = screenWidth * 254 / 455;
        int pwdHeight = screenHeight * 28 / 804;
        int pwdMarginTop = screenHeight * 454 / 804;
        int pwdMaringLeft = screenWidth * 122 / 455;
        RelativeLayout.LayoutParams lpPwd = new RelativeLayout.LayoutParams(pwdWidth, pwdHeight);
        lpPwd.topMargin = pwdMarginTop;
        lpPwd.leftMargin = pwdMaringLeft;
        llPwd.setLayoutParams(lpPwd);

    }

    /**
     * 页面控件做动画的处理
     */
    private void doAnim() {
        //太阳的动画
        ObjectAnimator sunAnim = ObjectAnimator.ofFloat(lvSun, "rotation", 0, 360);

        sunAnim.setDuration(12000);
        sunAnim.setRepeatCount(ValueAnimator.INFINITE);
        sunAnim.setRepeatMode(ValueAnimator.RESTART);
        ObjectAnimator sunAlphaAnim = ObjectAnimator.ofFloat(lvSun, "alpha", 1, 0.5f, 1);
        sunAlphaAnim.setRepeatCount(ValueAnimator.INFINITE);
        sunAlphaAnim.setRepeatMode(ValueAnimator.RESTART);
        sunAlphaAnim.setDuration(4000);

        //星星的动画
        ObjectAnimator xOneAnim = ObjectAnimator.ofFloat(xOne, "alpha", 1, 0, 1);
        ObjectAnimator xTwoAnim = ObjectAnimator.ofFloat(xTwo, "alpha", 1, 0, 1);
        ObjectAnimator xTheeAnim = ObjectAnimator.ofFloat(xThree, "alpha", 1, 0, 1);
        xOneAnim.setRepeatCount(ValueAnimator.INFINITE);
        xOneAnim.setRepeatMode(ValueAnimator.RESTART);
        xOneAnim.setDuration(4000);

        xTwoAnim.setRepeatCount(ValueAnimator.INFINITE);
        xTwoAnim.setRepeatMode(ValueAnimator.RESTART);
        xTwoAnim.setDuration(4500);

        xTheeAnim.setRepeatCount(ValueAnimator.INFINITE);
        xTheeAnim.setRepeatMode(ValueAnimator.RESTART);
        xTheeAnim.setDuration(5000);

        //恐龙的动画
        ObjectAnimator klAnim = ObjectAnimator.ofFloat(lvKL, "translationY", 0, -30, 0);
        klAnim.setDuration(2400);
        klAnim.setRepeatCount(ValueAnimator.INFINITE);
        klAnim.setRepeatMode(ValueAnimator.RESTART);

        //瓢虫的动画
        ObjectAnimator pcAnim = ObjectAnimator.ofFloat(lvPc, "translationX", 0, -30, 0, 25, 0);
        pcAnim.setDuration(5200);
        pcAnim.setRepeatCount(ValueAnimator.INFINITE);
        pcAnim.setRepeatMode(ValueAnimator.RESTART);

        animatorSet = new AnimatorSet();
        animatorSet.playTogether(sunAnim, xOneAnim, xTwoAnim, xTheeAnim, klAnim, pcAnim, sunAlphaAnim);

        animatorSet.setInterpolator(new LinearInterpolator());

        animatorSet.start();

    }

    /**
     * 初次进入同步状态的方法
     * 1.是否显示账号
     * 2.是否勾选记住账号
     */
    private void syncState() {

        //获取身份角色
        role = SPUtil.getString(this, SpKeys.ROLETYPE);

        //是否记住密码
        isRememberCount = SPUtil.getBoolean(this, SpKeys.ISRENMERCOUNT);

        if (isRememberCount) {
            //记住账号的操作
            mLvJzzh.setImageResource(R.drawable.checked);
            etTel.getEdittext().setText(SPUtil.getString(this, SpKeys.REMBERACCOUNT));
            etPwd.getEdittext().setText(SPUtil.getString(this, SpKeys.PASSWORD));
        } else {
            //不记住账号的操作
            mLvJzzh.setImageResource(R.drawable.unchecked);
            etTel.getEdittext().setText("");
            etPwd.getEdittext().setText("");
        }

        //教师与校长不需注册
        if ("2".equals(role) || "3".equals(role)) {
            lvCjzh.setVisibility(View.GONE);
        } else {
            lvCjzh.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 点击记住账号的操作
     */
    private void doRememberCount() {
        //对状态取反
        isRememberCount = !isRememberCount;
        if (isRememberCount) {
            mLvJzzh.setImageResource(R.drawable.checked);
        } else {
            mLvJzzh.setImageResource(R.drawable.unchecked);
        }
        SPUtil.put(this, SpKeys.ISRENMERCOUNT, isRememberCount);
    }


    /**
     * 点击登录后的操作
     */
    private void doLoginAction() {
        //获取手机号
        String tel = etTel.getEdittext().getText().toString().trim();

        //获取输入的密码
        String pwd = etPwd.getEdittext().getText().toString().trim();

        //判断非空处理
        if (TextUtils.isEmpty(tel)) {
            SnackbarUtil.ShortSnackbar(main, "手机号不能为空", 0).show();
            return;
        }


        //判断非空处理
        if (TextUtils.isEmpty(pwd)) {
            SnackbarUtil.ShortSnackbar(main, "密码不能为空", 0).show();
            return;
        }


        // 正则表达式判断密码
        if (!isPassword(pwd)) {
            SnackbarUtil.ShortSnackbar(main, "请输入6-20位数字或字母的密码", 0).show();
            return;
        }


        if (isRememberCount) {
            //如果是记录账号和密码,则记录输入的账号和密码
            //记住账号
            SPUtil.put(LoginActivity.this, SpKeys.REMBERACCOUNT, tel);

            //记住密码
            SPUtil.put(LoginActivity.this, SpKeys.PASSWORD, pwd);
        }

        //请求登录接口
        loginHttp(tel, pwd);
    }

    /**
     * 判断密码的正则
     */
    private boolean isPassword(String pwd) {
        String regExp = ("^[a-zA-Z0-9]{4,20}+$");
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(pwd);
        return m.matches();

    }


    /**
     * 请求登录接口
     */
    private void loginHttp(final String tel, final String pwd) {
        //加密
        String acc = "";
        String pswd = "";
        String registration_id = "";
        try {
            acc = AESOperator.getInstance().encrypt(tel);
            pswd = AESOperator.getInstance().encrypt(pwd);
            registration_id = AESOperator.getInstance().encrypt(SPUtil.getString(this, SpKeys.JPUSH_ID));
        } catch (Exception e) {
            e.printStackTrace();
        }
        CustomDialogManager.show(this, "登录中...");
        Map<String, String> map = new HashMap<>();
        map.put("type", "2");

        map.put("acc", acc.trim() + "");
        map.put("role", role + "");
        map.put("pswd", pswd.trim() + "");
        map.put("registration_id", registration_id.trim() + "");
        map.put("platform", "2");

        LogUtils.iTag("test", "请求参数是:acc=" + acc.trim() + "&role=" + role + "&registration_id=" + registration_id.trim()
                + "&platform=2" + "&pswd=" + pswd.trim());

        HttpUtils.post(HttpAddress.LOGIN, map, new HttpCallBack<LoginInfo>() {
            @Override
            public void onSuccess(LoginInfo info) {
                CustomDialogManager.dissmiss();

                //判断返回状态码  101103为registration_id为空，但密码正确登录成功
                if ("200".equals(info.getResult()) || "101103".equals(info.getResult())
                        || "101104".equals(info.getResult())) {
                    //登录成功 1已登录 0未登录
                    SPUtil.put(LoginActivity.this, SpKeys.ISLOGIN, "1");

                    //保存账号
                    SPUtil.put(LoginActivity.this, SpKeys.ACCOUNT, tel);

                    //保存姓名
                    SPUtil.put(LoginActivity.this, SpKeys.NAME, info.getName());

                    //保存头像
                    SPUtil.put(LoginActivity.this, SpKeys.ICON, info.getIcon());

                    //保存TOKEN1
                    SPUtil.put(LoginActivity.this, SpKeys.TOKEN1, info.getToken1());

                    //保存TOKEN2
                    SPUtil.put(LoginActivity.this, SpKeys.TOKEN2, info.getToken2());

                    //保存学校ID
                    SPUtil.put(LoginActivity.this, SpKeys.SCHOOLID, info.getSchoolId());

                    //保存学校名称
                    SPUtil.put(LoginActivity.this, SpKeys.SCHOOLNAME, info.getSchoolName());

                    //保存是否隐藏群组
                    SPUtil.put(LoginActivity.this, SpKeys.DISABLEGROUP, info.getDisableGroup());

                    //使用专场动画根据角色类型跳转到不同的界面,注意:学生端还需要判断是否是第一次进入APP
                    String type = SPUtil.getString(LoginActivity.this, SpKeys.ROLETYPE);


                    LogUtils.iTag("test", "登录的信息是:");
                    LogUtils.iTag("test", GsonUtil.objectToJson(info));


                    //学生端
                    if ("0".equals(type)) {

                        //保存自己的老师
                        SPUtil.put(LoginActivity.this, SpKeys.TEACHER, info.getTeacher());

                        //保存自己的班级ID
                        SPUtil.put(LoginActivity.this, SpKeys.CLASSNUM, info.getClassnum());


                        Log.i("test", info.getTeacher() + "CLASSNUM:" + info.getClassnum());
                        //性别  0默认  1男  2女
                        SPUtil.put(LoginActivity.this, SpKeys.SEX, info.getSex());

                        if ("1".equals(info.getHaspet())) {
                            //已拥有宠物
                            //保存宠物昵称
                            SPUtil.put(LoginActivity.this, SpKeys.PETNAME, info.getNICK_NAME());

                            //保存宠物类型
                            SPUtil.put(LoginActivity.this, SpKeys.SERVICEPETTYPE, info.getPET_ID());

                            //宠物性别
                            SPUtil.put(LoginActivity.this, SpKeys.PETGENDAR, info.getSex());

                            //跳转到学生端主界面
                            UiUtils.startActivity(LoginActivity.this, StudentMainActivity.class);

                        } else if ("0".equals(info.getHaspet())) {
                            //未拥有宠物,跳转到宠物领取界面
                            UiUtils.startActivity(LoginActivity.this, StudentGetpetOneActivity.class);
                        }
                    }

                    //家长端
                    if ("1".equals(type)) {
                        //保存老师
                        SPUtil.put(LoginActivity.this, SpKeys.TEACHER, info.getTeacher());
                        //保存班级ID
                        SPUtil.put(LoginActivity.this, SpKeys.CLASSNUM, info.getClassnum());
                        UiUtils.startActivity(LoginActivity.this, ParentMainActivity.class);
                    }

                    //教师端
                    if ("2".equals(type)) {
                        //保存USERTYPE
                        SPUtil.put(LoginActivity.this, SpKeys.USERTYPE, "1");
                        UiUtils.startActivity(LoginActivity.this, TeacherMainActivity.class);
                    }

                    //校长端
                    if ("3".equals(type)) {
                        UiUtils.startActivity(LoginActivity.this, MasterMainActivity.class);
                    }

                    finish();

                } else {
                    //登录失败
                    StateCodeUtils.showSateCode(info.getResult());
                }
            }

            @Override
            public void onError(String e) {
                //请求失败
                CustomDialogManager.dissmiss();
                ToastUtils.showShort(BaseApplication.ERROR);
            }
        });
    }


    /**
     * 页面控件点击事件
     *
     * @param v
     */
    @OnClick({R.id.bt_login, R.id.lv_cjzh, R.id.tv_forget_pwd, R.id.ll_jzmm})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_login:
                //登录
                if (isDoubleClick(v)) {
                    SnackbarUtil.ShortSnackbar(main, getResources().getString(R.string.message), 0).show();
                } else {
                    doLoginAction();
                }
                break;
            case R.id.lv_cjzh:
                //创建账号
                if (!isDoubleClick(v)) {
                    UiUtils.startActivity(LoginActivity.this, RegisterActivity.class);
                }
                break;
            case R.id.tv_forget_pwd:
                //忘记密码
                if (!isDoubleClick(v)) {
                    UiUtils.startActivity(LoginActivity.this, ResetPasswordActivity.class);
                }

                break;
            case R.id.ll_jzmm:
                //记住账号
                doRememberCount();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        if (null != animatorSet) {
            animatorSet.cancel();
        }
        super.onDestroy();
    }
}
